#include "socket.hpp"
#include "TcpServer.hpp"
#include "protocol.hpp"

class ServerCal
{
public:
    ServerCal()
    {}

    ~ServerCal()
    {}

    Response CalculatorHelper(Request& rt)
    {
        Response res;
        switch(rt._op)
        {
            case '+':
                res._res = rt._x + rt._y;
                break;
            case '-':
                res._res = rt._x - rt._y;
                break;
            case '*':
                res._res = rt._x * rt._y;
                break;
            case '/':
                res._res = rt._x / rt._y;
                break;
        }
        // std::cout << "CalculatorHelper:: res._res = " << res._res << std::endl;
        res._code = 0;
        return res;
    }

    std::string Calculator(std::string& package)
    {
        sleep(1);
        
        std::string s;
        if(!Decode(package, s)) return "";

        Request rt;
        if(!rt.Deserialize(s)) return "";

        Response res = CalculatorHelper(rt);

        res.Serialize(&s);
        s = Encode(s);
        
        return s;
    }
private:

};

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " + port" << std::endl; 
        return 1;
    }
    uint16_t serverport = std::stoi(argv[1]);
    std::cout << "serverport = " << serverport << std::endl;
    ServerCal sc;
    std::string ip = "0.0.0.0";
    TcpServer* pts = new TcpServer(serverport, ip, std::bind(&ServerCal::Calculator, &sc, std::placeholders::_1));

    pts->Init();
    pts->Start();
    
    
    return 0;
}